import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, getUserInfo } from '@/api/user'
import { constantRoutes, resetRouter } from '@/router'
const state = {
  token: getToken(),
  userInfo: {}, // 存放了个人信息
  router: constantRoutes // 存放了静态路由
}

const mutations = {
  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  removeToken(state, token) {
    state.token = null
    removeToken()
  },
  setUserInfo(state, result) {
    state.userInfo = result
  },
  setRoutes(state, newRouter) {
    state.routes = [...constantRoutes, ...newRouter]
  }
}

const actions = {
  // 登录
  async login(context, data) {
    const token = await login(data)
    context.commit('setToken', token)
    resetRouter()
  },

  // 获取个人信息
  async getUserInfo(store) {
    const result = await getUserInfo()
    store.commit('setUserInfo', result)
    return result
  },
  // 退出登录
  logout(store) {
    store.commit('removeToken')
    store.commit('setUserInfo', {})
    // 重置路由
    resetRouter()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
